<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" destroyOnClose showFooter :title="getTitle" :width="drawerWith" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #startEndTimeTip="{ model, field }"> <p style="color: red">有明确营业时间的就返回"09:00-21:00"格式;无明确营业时间的可返回“最早航班-最晚航班”格式</p></template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" name="viponlyDrawer" setup>
import { computed, defineEmits, ref, unref } from 'vue';
import { BasicForm, useForm } from '@apps/antd-admin/src/components/Form/index';
import { BasicDrawer, useDrawerInner } from '@apps/antd-admin/src/components/drawer';
import { formSchema } from '../data/data';
import { add, getViponlyDetail, update } from '../data/api';
import { useAppInject } from '@apps/antd-admin/src/hooks/web/use-app-inject';
const { getIsMobile } = useAppInject();
const drawerWith = ref('40%');
if (unref(getIsMobile)) {
  drawerWith.value = '80%';
}
const isUpdate = ref(true);
const emit = defineEmits(['success', 'register']);
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 90,
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async data => {
  resetFields();
  setDrawerProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;

  if (unref(isUpdate)) {
    let record = data.record;
    let viponlyId = record.viponlyId;
    let result = await getViponlyDetail({
      viponlyId: viponlyId,
      handlerName: 'busViponlyGetHandler',
    });
    setFieldsValue({
      ...result,
    });
  } else {
    setFieldsValue({ airportId: data.airportId });
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增贵宾通道' : '编辑贵宾通道'));

async function handleSubmit() {
  try {
    const values = await validate();
    setDrawerProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await update(values);
    } else {
      await add(values);
    }
    console.log(values);
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
